import { defineStore } from 'pinia';
import { ref, Ref } from 'vue';

type ConnectionStatus = 'disconnected' | 'connecting' | 'connected' | 'error';
type Subscriber = (data: any) => void;

export const useWebsocketStore = defineStore('websocket', () => {
  const wsConnection: Ref<WebSocket | null> = ref(null);
  const connectionStatus: Ref<ConnectionStatus> = ref('disconnected');
  const subscribers: Record<string, Subscriber[]> = {};
  const wsUrl: Ref<string> = ref('ws://127.0.0.1:9998');
  function connectWebSocket(url: string): WebSocket {
    wsUrl.value = url;
    if (wsConnection.value) {
      disconnectWebSocket();
    }
    connectionStatus.value = 'connecting';
    const ws = new WebSocket(url);

    ws.onopen = () => {
      console.log('WebSocket连接已建立');
      connectionStatus.value = 'connected';
    };
    ws.onerror = (error) => {
      console.error('WebSocket错误:', error);
      connectionStatus.value = 'error';
    };

    ws.onclose = () => {
      console.log('WebSocket连接已关闭');
      connectionStatus.value = 'disconnected';
    };

    ws.onmessage = (event) => {
      const data = JSON.parse(event.data);
      console.log('websocket收到消息', data);
      notifySubscribers(data.type, data.data);
    };

    wsConnection.value = ws;
    return ws;
  }

  function disconnectWebSocket(): void {
    if (wsConnection.value) {
      wsConnection.value.close();
      wsConnection.value = null;
      connectionStatus.value = 'disconnected';
    }
  }

  function subscribe(messageType: string, callback: Subscriber): void {
    if (!subscribers[messageType]) {
      subscribers[messageType] = [];
    }
    subscribers[messageType].push(callback);
  }

  function unsubscribe(messageType: string, callback: Subscriber): void {
    if (subscribers[messageType]) {
      subscribers[messageType] = subscribers[messageType].filter((cb) => cb !== callback);
    }
  }

  function notifySubscribers(messageType: string, data: string): void {
    if (subscribers[messageType]) {
      console.log('有订阅者', messageType);
      subscribers[messageType].forEach((callback) => callback(data));
    } else {
      console.log('没有订阅者', messageType);
    }
  }

  return {
    wsUrl,
    wsConnection,
    connectionStatus,
    connectWebSocket,
    disconnectWebSocket,
    subscribe,
    unsubscribe,
  };
});
